package com.example.queue09.queue;

/**
 * 用数组实现队列
 * @auther lijiewei
 * @date 2021/8/23 11:01
 */
public class ArrayQueue {

    private String[] items;
    /** 数组大小. */
    private int size = 0;
    /** 头下标. */
    private int head = 0;
    /** 尾下标. */
    private int tail = 0;

    public ArrayQueue(int capacity) {
        if (capacity <= 0) {
            throw new RuntimeException("容量必须大于0");
        }
        items = new String[capacity];
        size = capacity;
    }

    /**
     * 入队
     * @param item 元素
     * @return
     * @author lijiewei
     * @date   2021/8/23 11:11
     */
    public boolean enqueue(String item) {
        //数组满了
        if(tail == size) {
            return false;
        }
        items[tail] = item;
        tail++;
        return true;
    }

    /**
     * 出队
     * @return
     * @author lijiewei
     * @date   2021/8/23 11:26
     */
    public String dequeue() {
        //数组为空
        if (head == tail) {
            return null;
        }
        String ret = items[head];
        head ++;
        return ret;
    }

    /**
     * 打印所有元素
     * @return
     * @author lijiewei
     * @date   2021/8/23 13:59
     */
    public void printAll() {
        for (int i = head; i < tail; i++) {
            System.out.print(items[i] + " ");
        }
        System.out.println();
    }
}
